package com.fu.shop.controller;

import com.fu.core.common.BusinessException;
import com.fu.core.common.ExceptionCode;
import com.fu.core.common.JsonResult;
import com.fu.core.util.OSSUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.UUID;

/**
 * @author 付龙江
 * @date 2022/2/5 15:13
 */
@RestController
@CrossOrigin
public class OSSController {
    final static public String BUCKET = "http://42.192.17.119/ossImg/";
    @PostMapping(value = "/ossUploadFile")
    public Map<String, Object> upload(MultipartFile file) throws Exception {

        // 得到原始文件名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename ==null){
            throw new BusinessException(ExceptionCode.PICTURE_NOT_EXIST);
        }
        //生成一个uuid防止文件名重复
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 从原始文件名中获取后缀,作为新添加的文件的文件名后缀(匹配)
        String subfix = originalFilename.substring(originalFilename.indexOf(".") + 1);

        // 通过Context获取当前程序的根路径
        String filePath = "reallyFruit/" + uuid + "." + subfix;
        //将图片上传到云端
        OSSUtil.upload(filePath, file.getInputStream());
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setMsg("文件上传成功");
        jsonResult.setField("data",BUCKET+filePath);
        return jsonResult.getMap();
    }
}
